package dd.prog2.musterExercises.ws12set03_function;

import rl.util.painttool.AbstractController;
import rl.util.painttool.PaintTool;

public class FunctionPlotter extends PaintTool {

	private double pixelWidth = -1;
	private double pixelHeight = -1;
	private double minX;
	private double maxX;
	private double minY;
	private double maxY;

	public FunctionPlotter(AbstractController controller) {
		super(controller);
	}

	public void addCoordinateSystem(int minX, int maxX, int minY, int maxY) {
		this.minX = minX;
		this.maxX = maxX;
		this.minY = minY;
		this.maxY = maxY;
		setPixelDimensions();
		addLine(xView(minX), yView(0), xView(maxX), yView(0));
		addLine(xView(0), yView(minY), xView(0), yView(maxY));
		addLine(xView(1), yView(0)-2, xView(1), yView(0)+2);
		addLine(xView(0)-2, yView(1), xView(0)+2, yView(1));
	}

	public void addFunction(Function f) {
		if (pixelWidth < 0)
			setPixelDimensions();
		int yViewLast = 0;
		for (int xView = 0; xView < getCanvas().getWidth(); xView++) {
			double x = minX + xView*pixelWidth;
			int yView = yView(f.map(x));
			if (xView > 0) {
				addLine(xView-1, yViewLast, xView, yView);
			}
			yViewLast = yView;
		}
	}

	@Override
	public void clearCanvas() {
		pixelWidth = -1;
		minX = -1;
		maxX = 1;
		minY = -1;
		maxY = 1;
		super.clearCanvas();
	}

	private void setPixelDimensions() {
		pixelWidth = (maxX - minX) / getCanvas().getWidth();
		pixelHeight = (maxY - minY) / getCanvas().getHeight();
	}
	
	private int xView(double x) {
		return (int) Math.round((x-minX) / pixelWidth);
	}
	
	private int yView(double y) {
		return (int) Math.round((maxY-y) / pixelHeight);
	}
}
